#!/usr/bin/python3
# by Sun Smallwhite <niasw@pku.edu.cn>(https://github.com/niasw)

import csv
import numpy
import scipy.sparse

def linkCSV2adjMat(filename,indexstart=0,withdata=False):
  '''
# Load links data in CSV format
# by Sun Smallwhite <niasw@pku.edu.cn>(https://github.com/niasw)

# input:
#  links
#  NOTICE: input paper index begin with 0
# output:
#  adjacent matrix
  '''
  flinks=open(filename,'r');
  reader=csv.reader(flinks);
  linksRow=[]; # adjacent matrix (sparse) row
  linksCol=[]; # adjacent matrix (sparse) column
  linksVal=[]; # adjacent matrix (sparse) value
  for it in reader:
   linksRow.append(int(it[0])-indexstart); # input data begin with 1
   linksCol.append(int(it[1])-indexstart); # inner data begin with 0
   if (withdata):
     linksVal.append(numpy.float64(it[2]));
   else:
     linksVal.append(1.);
  maxNum=max(max(linksRow),max(linksCol))+1;
  adjmat=scipy.sparse.coo_matrix((numpy.array(linksVal), (numpy.array(linksRow), numpy.array(linksCol))),shape=(maxNum,maxNum));
  return adjmat;

def loadCSVvector(filename):
  '''
# Load 1 column CSV as a vector
  '''
  fvec=open(filename,'r');
  reader=csv.reader(fvec);
  vect=numpy.array([int(it[0]) for it in reader]);
  return vect;

